'''
Created on 2011-12-11

@author: jiangxd
'''
import urllib
import string
from HTMLParser import HTMLParser
from xml.dom import *
from xml.sax.saxutils import unescape,escape

BASE_URI = 'http://dict.baidu.com/s?wd=%s&f=3&dt=explain'

class ParserEnd(Exception):
	def __str__(self):
		return "This parser is end"

class MyParser(HTMLParser):
	def __init__(self):
		HTMLParser.__init__(self)
		self.yinbiaoStart = False
		self.explainStart = False
		self.realwordStart = False
		self.depth = 0
		self.yinbiao_content = ''
		self.explain_content = ''
		self.realword = ''
		
	def _get_attr(self,attrs,attr_name):
		for pair in attrs:
			if pair[0] == attr_name:
				return pair[1]

	def handle_starttag(self, tag, attrs):
		if tag == 'span' and 'enword' == self._get_attr(attrs,'class'):
			self.realwordStart = True
		if tag == 'span' and 'pinyin' == self._get_attr(attrs,'class'):
			self.yinbiaoStart = True
		if tag == 'div' and 'explain' == self._get_attr(attrs,'class'):
			self.explainStart = True
		if self.yinbiaoStart or self.explainStart:
			self.depth += 1

	def handle_endtag(self, tag):
		if self.realwordStart:
			self.realwordStart = False
		if self.yinbiaoStart:
			self.depth -= 1
			self.yinbiao_content += ' '
		if self.explainStart:
			if tag == 'div' or tag == 'br':
				self.explain_content += "\n"
			self.depth -= 1
		if self.depth <= 0:
			if self.explainStart:
				raise ParserEnd()
			self.yinbiaoStart = False
			self.explainStart = False

	def handle_data(self, data):
		if self.realwordStart:
			self.realword = data.decode('gbk')
		if self.yinbiaoStart:
			self.yinbiao_content += data.decode('gbk')
		if self.explainStart:
			self.explain_content += data.decode('gbk')
	
	def get_yinbiao(self):
		return self.yinbiao_content.strip()
	
	def get_explain(self):
		return self.explain_content.strip()
	
	def get_realword(self):
		return self.realword.strip()

	def unescape(self, s):
		return s

	def handle_charref(self,name):
		if not name.startswith('x'): # decimal
			self.yinbiao_content += unichr(int(name))

def get_content(url):
	f = urllib.urlopen(url)
	psr = MyParser()
	try:
		psr.feed(f.read())

		psr.close()
	except ParserEnd:
		pass
	f.close()
	return psr.get_explain(),psr.get_yinbiao(),psr.get_realword()

def lookup(word):
	url = BASE_URI % word
	return get_content(url)
